import {
  ApiRootUrl,
  apiList
} from '../../../config/index.js'
import Dialog from '../../../@vant/weapp/dialog/dialog';
import {
  IMG_PATH
} from '../../../config/index.js'
import {
  request,formatStringTime
} from "../../../utils/util.js"
import Toast from '../../../@vant/weapp/toast/toast';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IMG_PATH: IMG_PATH,
    birthday: '',
    height: 0,
    currentDate: new Date().getTime(),
    lizhiminDate: new Date(1950, 1, 1).getTime(),
    lizhimaxDate: new Date(2030,1,1).getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}`;
      } else if (type === 'month') {
        return `${value}`;
      }
      return value;
    },
    lizhiTimeShow: false,
    lizhiTime: '请选择',
    zhusuShowColumns: ["全部",'是', '否'],
    zhusuShow: false,
    tongzhiShow: false,
    allpendingchecked: false,
    allTap: false,
    allTap1:false,
    allchecked: false,
    tongzhimessage: '',
    pageSize: 20,
    pageNumber: 1,
    total: 0,
    dangerId:"",
    allIsRoomType:"0",
    buildNum:"",
    unitNum:"",
    roomNumber:"",
    badNumber:"",
    buildAddr:"",
    determineList: [],
    pendingList: [],
    passList: [],
    item:{},
    haveCheckedArr:[], //已选列表
    minDate: new Date(2020, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    sourceShow: false,
    dangerShow: false,
    timeshow: false,
    statusBarHeight: '',
    active: 0,
    searchValue: '',
    isLoad:false,
    sourceName: '劳务公司',
    iszhusu: '是否住宿',
    time: '选择时间',
    danger: '备案登记',
    sourceShowColumns: [],
    dangerShowColumns: [{
      id: '',
      text: '全部'
    },{
      id: '0',
      text: '未提交'
    }, {
      id: '1',
      text: '已提交'
    }, {
      id: '2',
      text: '备案中'
    }, {
      id: '3',
      text: '已备案'
    }],
    tabList: [{
      title: '全部',
    }, {
      title: '在宿人员',
    }, {
      title: '未住宿人员',
    }]
  },
  companyClick() {
    this.setData({
      sourceShow: true
    })
  },
  dangerShowClose() {
    this.setData({
      dangerShow: false
    })
  },
  zhusuShowClose() {
    this.setData({
      zhusuShow: false
    })
  },
  zhusuClick() {
    this.setData({
      zhusuShow: true
    })
  },
  dangerClick() {
    this.setData({
      dangerShow: true
    })
  },
  sourceShowClose() {
    this.setData({
      sourceShow: false
    })
  },
  enterRoom(tbEmployeeDormDOs){
    let params = {
      tbEmployeeDormDOs:tbEmployeeDormDOs
    }
    Toast.loading({
      message: '登记中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    this.setData({
      tongzhiShow:false,
    })
    request(apiList.enterRoom,params).then(res =>{
      wx.showToast({
        title: '登记成功!',
      })
      this.getOnJob(2)
    }).catch(err =>{
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  zhusuShowConfirm(event) {
    console.log(event.detail.value)
    this.setData({
      iszhusu: event.detail.value,
      zhusuShow: false
    },()=>{
      let type = 0;
      if(event.detail.value == "是"){
        type = 1
      }else if(event.detail.value == "否"){
        type = 2
      }else if(event.detail.value == "全部"){
        type = 0
      }
      this.setData({
        allIsRoomType:type
      })
      this.getOnJob(type)
    })
  },
  dangerShowConfirm(event) {
    this.setData({
      danger: event.detail.value.text,
      dangerId: event.detail.value.id,
      dangerShow: false
    },()=>{
      if(this.data.active == 0 ){
        this.getOnJob(this.data.allIsRoomType);
      }else{
        this.getOnJob(this.data.active);
      }
    })
  },
  sendClick(){
    
    if(this.data.lizhiTime == "请选择"){
      Toast("入宿时间不能为空")
      return
    }
    if(this.data.buildAddr == ""){
      Toast("宿舍地址不能为空")
      return
    }
    if(this.data.buildNum == ""){
      Toast("宿舍名称不能为空")
      return
    }
    let haveCheckedArr = this.data.haveCheckedArr;
    let requestArr=[]
    if(haveCheckedArr.length > 0){
      
    for(let i= 0;i<haveCheckedArr.length;i++){
      let obj = {
        buildNum:this.data.buildNum, //楼号
        unitNum:this.data.unitNum,//单元号
        roomNum:this.data.roomNumber,//房间号
        bedNum:this.data.badNumber,//床号
        entryDorm :formatStringTime(this.data.lizhiTime),//入宿时间
        id:haveCheckedArr[i].id,
        dormAddr:this.data.buildAddr,
        openId:haveCheckedArr[i].openId,
        name:haveCheckedArr[i].name,
        identity:haveCheckedArr[i].identity,
      }
      requestArr.push(obj)
    }
    }else{
      let obj = {
        buildNum:this.data.buildNum, //楼号
        unitNum:this.data.unitNum,//单元号
        roomNum:this.data.roomNumber,//房间号
        bedNum:this.data.badNumber,//床号
        entryDorm :formatStringTime(this.data.lizhiTime),//入宿时间
        id:this.data.item.id,
        dormAddr:this.data.buildAddr,
        openId:this.data.item.openId,
        name:this.data.item.name,
        identity:this.data.item.identity,
      }
      requestArr.push(obj)
    }
    this.enterRoom(requestArr)
  },
  timeClick() {
    this.setData({
      timeshow: true
    })
  },
  getOnJob(type) {
    console.log("type======>",type)
    let params = {
      labourCode: this.data.sourceCode,
      // labourCode:"002",
      name: this.data.searchValue,
      phone: "",
      dormStatus:type == 0 ? null :type == 1 ? 2 :type == 2 ? 0 : null,
      surveyStatus: this.data.dangerId == ""?"":Number(this.data.dangerId),
      pageNumber:1,
      pageSize:20,
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    
    request(apiList.onJob, params).then((res) => {
     console.log("请求结果=====>",res)
     if(this.data.active == 2){
       let arr = []
       for(let i = 0; i < res.data.list.length; i++ ){
        res.data.list[i].checked = false
        arr.push(res.data.list[i])
       }
      this.setData({
        total:res.data.total,
        determineList:arr
      })
     }else{
      this.setData({
        total:res.data.total,
        pendingList:res.data.list
      })
     }
      
      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  getSearchValue(e) {
    let value = e.detail;
    this.setData({
      searchValue: value
    }, () => {
      if(this.data.active == 0 ){
        this.getOnJob(this.data.allIsRoomType);
      }else{
        this.getOnJob(this.data.active);
      }
    })
  },
  sourceShowConfirm(event) {
    let text = event.detail.value.text
    if(text == "全部"){
      text = "劳务公司"
    }
    this.setData({
      sourceName: text,
      sourceCode:event.detail.value.id,
      sourceShow: false
    },()=>{
      if(this.data.active == 0 ){
        this.getOnJob(this.data.allIsRoomType);
      }else{
        this.getOnJob(this.data.active);
      }
    })
  },
  tabClick(event) {
    this.setData({
      active: event.detail.index,
      pageNumber:1
    },()=>{
      this.getOnJob(this.data.active)
    })
  },
  birthdadInput(event) {
    let time = this.formatDate(event.detail);
    console.log(time);
    this.setData({
      birthday: time,
    });
  },
  lizhiTimeClose() {
    this.setData({
      lizhiTimeShow: false
    })
  },
  familybirthdayConfirm(event) {
    console.log(event);
    let birthday = this.data.birthday;
    this.setData({
      lizhiTime: birthday,
      lizhiTimeShow: false,
      tongzhiShow: true
    })
  },
  backClick(event) {
    console.log(event);
    wx.navigateBack();
    // Dialog.confirm({
    //   title: '返回',
    //   message: '请确认是否返回？',
    // }).then(() => {
    //   wx.navigateBack();
    // }).catch(() => {
    //   console.log('取消')
    // });
  },
  formatDate(date) {
    var date = new Date(date);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    return YY + MM + DD;
  },
  timeConfirm(event) {
    const [start, end] = event.detail;
    this.setData({
      timeshow: false,
      time: `${this.formatDate(start)} - ${this.formatDate(end)}`,
    });
    console.log(this.data.time)
  },
  refendClick(event) {
    console.log(event);
    this.setData({
      tongzhiShow: true
    })
  },
  refendpendingClick(event) {
    console.log(event);
  },
  pendingChange1(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.pendingList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    let flag = true; 
    let objArr= []; //已选数组
    for (let i = 0; i < dataList.length; i++) {
      if (!dataList[i].checked) {
        flag = false
      }else{
        objArr.push(dataList[i])
      }
    }
    if(objArr.length > 8){
      Toast("最多只能入宿八个人员!")
      return
    }
    this.setData({
      pendingList: dataList,
      allpendingchecked: flag,
      haveCheckedArr:objArr
    })
    let list = dataList.map(value => value['checked']);
    if (list.includes(true)) {
      this.setData({
        allTap1: true
      })
    } else {
      this.setData({
        allTap1: false
      })
    }
  },
  pendingChange(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    let flag = true; 
    let objArr= []; //已选数组
    for (let i = 0; i < dataList.length; i++) {
      if (!dataList[i].checked) {
        flag = false
      }else{
        objArr.push(dataList[i])
      }
    }
    if(objArr.length > 8){
      Toast("最多只能入宿八个人员!")
      return
    }
    this.setData({
      determineList: dataList,
      allpendingchecked: flag,
      haveCheckedArr:objArr
    })
    let list = dataList.map(value => value['checked']);
    if (list.includes(true)) {
      this.setData({
        allTap: true
      })
    } else {
      this.setData({
        allTap: false
      })
    }
    

  },
  dengjiClick(e) {
    let type = Number(e.currentTarget.dataset.type)
    console.log(type)
    if(type == 0){
      let item = e.currentTarget.dataset.item
      this.setData({
        tongzhiShow: true,
        item:item
      })
    }else if(type == 1){
      let ids = []
      for(let i=0;i<this.data.pendingList.length;i++){
        if(this.data.pendingList[i].checked){
          let obj = {
            id:this.data.pendingList[i].id,
            openId:this.data.pendingList[i].openId,
            componentCode:this.data.pendingList[i].componentCode,
            surveyStatus:"1",
          }
          ids.push(obj)
        }
      }
      this.checkLabal(ids)
    }
  },
  checkLabal(ids){
    let params = {
      ids:ids,
      flag:"2",
    }
    Toast.loading({
      message: '处理中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.checkLabor,params).then((res) => {
      console.log("请求结果=====>",res)
      Toast.clear();
      wx.showToast({
        title: '备案登记成功',
      })
      this.getOnJob(this.data.active)
    }).catch((err) => {
      console.log("err==>",err)
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  lizhiTimeClick() {
    this.setData({
      lizhiTimeShow: true,
    })
  },
  pendingDetailsClick(event) {
    console.log(event);
    wx.navigateTo({
      url: `../detail/detail?id=${event.target.dataset.id}&type=${event.target.dataset.type}`
    })
  },
  refendpendingClick(event) {
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${event.target.dataset.id}`
    })
  },
  passChange(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    this.setData({
      passList: dataList
    })
    if (event.detail) {
      this.setData({
        allpendingchecked: true
      })
    } else {
      let list = dataList.map(value => value['checked']);
      if (list.includes(true)) {
        this.setData({
          allpendingchecked: true
        })
      } else {
        this.setData({
          allpendingchecked: false
        })
      }

    }
  },
  timeClose() {
    this.setData({
      timeshow: false
    });
  },
  pendingallChange(event) {
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allpendingchecked: event.detail,
      determineList: dataList
    })
  },
  passallChange(event) {
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allchecked: event.detail,
      passList: dataList,
      allTap: event.detail,
    })
  },
  tongzhiClose() {
    this.setData({
      tongzhiShow: false,
      tongzhimessage: ''
    })
  },
  getOnJobPage(type) {
    console.log("type======>",type)
    let params = {
      labourCode: this.data.sourceCode,
      // labourCode:"002",
      name: this.data.searchValue,
      phone: "",
      // isDorm:type == 0 ? null :type == 1 ? 1 :type == 2 ? 0 : null,
      dormStatus:type == 0 ? null :type == 1 ? 2 :type == 2 ? 0 : null,
      surveyStatus: this.data.dangerId == ""?"":Number(this.data.dangerId),
      pageNumber:this.data.pageNumber+1,
      pageSize:20,
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.onJob, params).then((res) => {
     console.log("请求结果=====>",res)
     if(this.data.active == 2){
       let arr = []
       for(let i = 0; i < res.data.list.length; i++ ){
        res.data.list[i].checked = false
        arr.push(res.data.list[i])
       }
      this.setData({
        total:res.data.total,
        pageNumber: this.data.pageNumber + 1,
        determineList:this.data.determineList.concat(arr),
        isLoad:false
      })
     }else{
      this.setData({
        total:res.data.total,
        pageNumber: this.data.pageNumber + 1,
        pendingList: this.data.pendingList.concat(res.data.list),
        isLoad:false
      })
     }
      
      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  loadMore(e) {
    if (this.data.active == 2) { // 未住宿人员
      if (this.data.determineList.length < this.data.total) {
        this.setData({
          isLoad:true
        })
        this.getOnJobPage(this.data.active)
      }
    } else { //全部 已住宿
      if (this.data.pendingList.length < this.data.total) {
        this.setData({
          isLoad:true
        })
        this.getOnJobPage(this.data.active)
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let query = wx.createSelectorQuery();
    query.select('.content').boundingClientRect(rect => {
      let height = rect.height;
      this.setData({
        statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
        height: wx.getSystemInfoSync().windowHeight - height,
        sourceShowColumns:app.globalData.companyList||[],
        userinfo:wx.getStorageSync('userinfo')
      })
    }).exec();
    this.getOnJob(this.data.active)
    // this.setData({
    //   sourceName: app.globalData.companyList[0].text,
    //   sourceCode:app.globalData.companyList[0].id
    // }, () => {
     
    // })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})